<?php
defined('BASEPATH') OR exit('No direct script access allowed');

$imageholder=unserialize($goods["thumb"]);
?>

                    <div class="row">
                        <div class="col-md-12">
                             <div class="box">
                                <div class="box-header with-border">
                                    <h3 class="box-title"><?php echo empty($goods)?"添加商品":"编辑商品";?></h3>
                                    <div class="pull-right">
                                    <?php if($goods):?>
                                    <!--<button class="btn btn-xs btn-info btn-flat" id="saveimage">转存图片</button>-->
                                    
                                    <button class="btn btn-xs btn-info btn-flat" id="syncimages">同步图片</button>
                                    <button class="btn btn-xs btn-warning btn-flat" id="syncdesc">同步描述</button>
                                    <button class="btn btn-xs btn-primary btn-flat" id="synccombine">同步变体</button>
                                    <a href="<?php echo $goods["source_url"];?>" target="_blank" class="btn btn-xs btn-success btn-flat">商品来源</a></div>
                                    <?php endif;?>
                                </div>
                                <div class="box-body">
                                    <?php echo $message;?>

                                    <?php echo form_open(current_url(), array('class' => 'form-horizontal', 'id' => 'form-edit_notice')); ?>
                                          <div class="form-group">
                                          <?php  echo '<label for="name"'._stringify_attributes(array('class' => 'col-sm-2 control-label')).'>商品名称</label>';?>
                                            <div class="col-sm-10">
                                                <span style="line-height:20px;"><?php echo form_input($gname);?></span>
                                            </div>
                                        </div>
                                        <div class="form-group">
                                          <?php  echo '<label for="price"'._stringify_attributes(array('class' => 'col-sm-2 control-label')).'>商品价格</label>';?>
                                            <div class="col-sm-10">
                                                <span style="line-height:20px;"><?php echo form_input($gprice);?></span>
                                            </div>
                                        </div>


                                         <div class="form-group">
                                            <label for="thumb" class="col-sm-2 control-label">商品图片</label>

                                            <div class="col-sm-10">
                                                 <?php
                                                     $piclist=unserialize($goods["thumb"]);
                                                     echo tpl_form_field_multi_image("thumb",$piclist);
                                                 ?>
                                            </div>
                                        </div>
                                       <div class="form-group">
                                          <?php  echo '<label for="desc"'._stringify_attributes(array('class' => 'col-sm-2 control-label')).'>商品介绍</label>';?>
                                            <div class="col-sm-10">
                                            <?php echo tpl_ueditor('desc', $goods['desc']);?>
                                            </div>
                                        </div>

                                        <?php if($goods):?>

                                        <div class="form-group">
                                            <div class="col-sm-offset-2 col-sm-10">
                                                <div class="btn-group">
                                        <?php echo form_button(array('type' => 'submit', 'class' => 'btn btn-primary btn-flat', 'content' => lang('actions_submit'))); ?>
                                                </div>
                                            </div>
                                        </div>
                                        <?php endif;?>
                              
                                        <div class="form-group">
                                        <?php  echo '<label for="option"'._stringify_attributes(array('class' => 'col-sm-2 control-label')).'>属性</label>';?>
                                            <div class="col-sm-10">                                           
                                                
                                                <div class="optionwarp" style="margin-bottom:40px;">
                                                    <?php if($goods):?>
                                                    <?php
                                                    $options=unserialize($goods['option']);
                                                    if ($options && isset($options["vv"]) && $options["vv"]):                                                
                                                    foreach($options["vv"] as $k=>$option):
                                                    ?>
                                                    <div>
                                                        <div class="" sindex="<?php echo $k;?>">标题 
                                                            <input type="text" name="optionname[<?php echo $k;?>]" value="<?php echo $option["name"];?>" class="form-control input-sm" style="width:auto;display:inline;"> <span class="btn btn-xs btn-info addval">添加值</span> <span class="btn btn-xs btn-danger removeoption">删除属性</span>
                                                        </div>

                                                        <div class="opwarp" style="margin-bottom:15px;">                                                    
                                                            <?php 
                                                            if($option["value"]):
                                                            foreach($option["value"] as $cc=>$v):?>
                                                            <div class="valcol"> 属性 
                                                            <input type="text" name="optionval[<?php echo $k;?>][]" value="<?php echo $v;?>" class="form-control input-sm" style="width:auto;display:inline;" place_holder="输入属性值，不能为空">
                                                            价格 <input type="text" name="optionprice[<?php echo $k;?>][]" value="<?php if (isset($option["price"])&&isset($option["price"][$cc])) echo $option["price"][$cc];?>" class="form-control input-sm" style="width:60px;display:inline;" place_holder="属性价格">

                                                            <?php if (isset($option["image"])&&isset($option["image"][$cc])):?>
                                                            图片 <input type="text" name="optionimg[<?php echo $k;?>][]" value="<?php echo $option["image"][$cc];?>" class="form-control input-sm optionimage" style="width:560px;display:inline;" place_holder="属性图片，没有请留空">
                                                            <?php 
                                                            $imageholder[]=$option["image"][$cc];
                                                            endif;?>
                                                            <button onclick="$(this).parent().remove();" class="btn"><i class="fa fa-remove"></i></button>
                                                            </div>
                                                            <?php 
                                                            endforeach;
                                                            endif;
                                                            ?>
                                                        </div>
                                                    </div>
                                                    <?php 
                                                    endforeach;
                                                    endif;
                                                    ?>
                                                    <?php endif;?>
                                                </div>

                                                <span class="btn btn-xs btn-flat btn-info" id="addoption">添加属性</span>
                                                <?php
                                                if(isset($options["newsku"]) && $options["newsku"]):
                                                ?>
                                                <span class="btn btn-xs btn-flat btn-success" id="skuprice">变体价格</span>
                                                <?php endif;?>

                                            </div>
                                        </div>


<!--
                                         <div class="form-group">
                                          <?php  echo '<label for="desc"'._stringify_attributes(array('class' => 'col-sm-2 control-label')).'>属性</label>';?>
                                            <div class="col-sm-10">
                                                <textarea class="form-control" style="height:200px;">
                                                <?php echo json_encode(unserialize($goods['option']),JSON_UNESCAPED_UNICODE);?>
                                                </textarea>
                                            </div>
                                        </div>
-->

                                        
                                        <div class="form-group">
                                            <div class="col-sm-offset-2 col-sm-10">
                                                <div class="btn-group">
                                                
                                                <?php echo form_hidden('id', $goods?$goods["id"]:0);?>
                                                <?php echo form_hidden('catid', $catid);?>
                                                
                                                    <?php echo form_button(array('type' => 'submit', 'class' => 'btn btn-primary btn-flat', 'content' => lang('actions_submit'))); ?>
                                                    <?php echo form_button(array('type' => 'reset', 'class' => 'btn btn-warning btn-flat', 'content' => lang('actions_reset'))); ?>
                                                    <?php echo anchor('admin/notice', lang('actions_cancel'), array('class' => 'btn btn-default btn-flat')); ?>
                                                </div>
                                            </div>
                                        </div>
                                    <?php echo form_close();?>
                                </div>
                            </div>
                         </div>
                    </div>
               

<script>
$(function(){

    var holdimage=<?php echo json_encode($imageholder);?>;
    var gid=<?php echo $goods?$goods["id"]:0;?>;



    <?php
            if(isset($options["newsku"]) && $options["newsku"]):
        ?>
        $("#skuprice").on('click',function(){
            
            let allpirce=eval('(<?php echo json_encode($options["newsku"]);?>)');
            let html='';
            $.each(allpirce, function(i, item){
                html+='<div class="form-group" style="margin-bottom:3px;"><input type="text" name="skuval[]" value="'+item["val"].join(' :: ')+'" placeholder="" class="form-control input-sm" style="width:400px;"> <input type="text" name="skuprice[]" value="'+item["price"]+'" placeholder="" class="form-control input-sm" style="width:100px;"></div>';
            });
            /*
            console.log(allpirce);
            */
            layer.open({
                type: 1,
                title: '请设置源变体价格',
                closeBtn: 1,
                offset : '100px',
                shadeClose: true,
                area:["800px","auto"],
                skin: 'layui-layer-lan',
                content: '<div style="padding:20px 30px;"><h4>速卖通所有变体价格</h4><form class="form-inline" id="skuform"><div class="llayui-layer-content" style="margin-bottom:10px;height:500px;overflow-y:scroll;" id="allop">'+html+'</div><div class="form-group"><input type="hidden" name="gid" value="'+gid+'"><span id="submitopprice2" class="btn btn-flat btn-info">更新变体价格</span></div></form></div>'
            });
        });
        $("body").on("click","#submitopprice2",function(){            
            shadow = layer.load(1, {
                shade: [0.1,'#000'] 
            });
            $.ajax({
                type:"post",
                url:"/backend/products/ajaxskupriceedit",
                dataType:"json",
                data:$("form#skuform").serialize(),
                error:function(){
                    layer.closeAll();
                    layer.msg("变体价格更新失败");
                },
                success:function(result){
                    layer.closeAll();
                    if(result["status"]!=1)
                    {
                        layer.msg(result["msg"]);                                    
                    }
                    else
                    {
                        layer.msg("变体价格更新成功");
                    }
                },
            });
        });
        <?php endif;?>

        $("#addoption").on('click',function(){
                if($(".opwarp").length>=3)
                {
                    layer.msg("最多添加3个属性");
                }
                else
                {
                    sindex=$(".opwarp").length;
                    $('<div><div sindex="'+sindex+'">标题 <input type="text" name="optionname['+sindex+']" value="" class="form-control input-sm" style="width:auto;display:inline;"> <span class="btn btn-xs btn-info addval">添加值</span> <span class="btn btn-xs btn-danger removeoption">删除属性</span></div><div class="opwarp" style="margin-bottom:15px;"></div></div>').appendTo($("div.optionwarp"));   
                }
                    
        });

        $(".optionwarp").on("click","span.removeoption",function(){
            $(this).parent().parent().remove();
        });

        $(".optionwarp").on("click","span.addval",function(){
            sindex=$(this).parent().attr("sindex");
            console.log(sindex);
            addinput='价格 <input type="text" name="optionprice['+sindex+'][]" value="" class="form-control input-sm" style="width:60px;display:inline;" place_holder="属性价格">图片 <input type="text" name="optionimg['+sindex+'][]" value="" class="form-control input-sm optionimage" style="width:560px;display:inline;" place_holder="属性图片，没有请留空">';
            baseinput='<div class="valcol"> 属性 <input type="text" name="optionval['+sindex+'][]" value="" class="form-control input-sm" style="width:auto;display:inline;" place_holder="输入属性值，不能为空">';
            if(sindex==0)
            {
                baseinput+=addinput;
            }
            $(baseinput+'<button onclick="$(this).parent().remove();" class="btn"><i class="fa fa-remove"></i></button></div>').appendTo($(this).parent().parent().find(".opwarp"));
        });


    require(["ueditor","jquery"],function(UE,$){
        var ue = UE.getEditor('desc');
        ue.ready(function() {
            ue.setHeight(600);
        });

    });

    $("body").on("click",".optionimage",function(){
        let orgfile = $(this).val();
        let inputblock = $(this);
        $('<input />', {
            id: 'upload',            
            type: 'file',
            style: 'display:none;',
        }).appendTo($(this).parent());
        $("body").off("change","#upload").on("change","#upload",function(){
            if($(this).val()=="") {
                return false;
            }
            FILES = $(this)[0].files[0];
            var formData = new FormData();
            formData.append("file", FILES);
            formData.append("name", 'newfile');
            formData.append("orgfile", orgfile);
            $.ajax({
                url: "/admin/Utility/optionimage",
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                dataType:"json",
                success: function (data) {
                    $(inputblock).val(data.path);
                }
                ,
                error : function (responseStr) {
                    //12出错后的动作
                    alert("出错啦");
                }
            });
            $("#upload").remove();
        });
        $("#upload").click();          

    });

    $("#syncimages").on("click",function(){
        shadow = layer.load(1, {
            shade: [0.1,'#000'] 
        });
        $.post("/backend/sites/product/syncimages/"+gid,{},function(result){
            layer.close(shadow);
            if(result.status==1)
            {
                layer.msg("同步成功");
            }
            else
            {
                layer.msg(result.msg);
            }            
        },dataType="json");
    });

    $("#syncdesc").on("click",function(){
        shadow = layer.load(1, {
            shade: [0.1,'#000'] 
        });
        $.post("/backend/sites/product/syncdesc/"+gid,{},function(result){
            layer.close(shadow);
            if(result.status==1)
            {
                layer.msg("同步成功");
            }
            else
            {
                layer.msg(result.msg);
            }            
        },dataType="json");
    });

    $("#synccombine").on("click",function(){
        shadow = layer.load(1, {
            shade: [0.1,'#000'] 
        });
        $.post("/backend/sites/product/synccombine/"+gid,{},function(result){
            layer.close(shadow);
            if(result.status==1)
            {
                layer.msg("同步成功");
            }
            else
            {
                layer.msg(result.msg);
            }            
        },dataType="json");
    });

    $("#saveimage").on("click",function(){

        layer.open({
        type: 1,
        skin: 'layui-layer-molv', //样式类名
        closeBtn: 0, //不显示关闭按钮
        anim: 2,
        shadeClose: false, //开启遮罩关闭
        content: "<div style='padding:20px 20px;' id='tipmsg'>共有"+holdimage.length+"条图片等待处理,请勿关闭窗口</div>"
        });
        let total = holdimage.length;
        let newurl=[];
        let download=0;
        

        function saveimage()
        {
            let defer = $.Deferred();
            $.each(holdimage, function(index,val) {
                $.ajax({
                    url: "/admin/Utility/fixed_pic",
                    type: "post",
                    data: {url:val},
                    dataType:"json",
                    success:function(result){
                        if(result.error==1)
                        {
                            layer.msg(result.msg);
                        }
                        else
                        {
                            newurl.push(result.path);
                            $("#tipmsg").text('已经完成下载图片 '+newurl.length+'/'+total+',请勿关闭窗口');
                            if(newurl.length==total){
                                defer.resolve(newurl.length+'/'+total);
                            }
                        }
                    }      
                });
            }); 
            return defer;
        }
        saveimage().then(function(){
            $("#tipmsg").text('正在更新产品图片,请勿关闭窗口');
            console.log(newurl);

            let updateimg=$.post("/backend/products/updateimage",{goodid:gid,org:holdimage,newurl:newurl},function(result)
            {

            },"json");

            $.when(updateimg).done(function(){
                $("#tipmsg").text('正在同步产品图片到网站,请勿关闭窗口');
                $.post("/backend/sites/product/updateimage/"+gid,{},function(result){
                    layer.closeAll();
                    location.href=location.href;
                });
                /*
                setTimeout(() => {
                    layer.closeAll();
                    location.href=location.href;
                }, 2000);
                */
            });
        });

    });

    var el = document.getElementsByClassName("multi-img-details")[0]
    Sortable.create(el, { /* options */ });
});
</script>
